"""
滑动拼图验证码
使用程序通过滑动拼图验证码的校验
目标站点：http://www.porters.vip/captcha/jigsawCanvas.html
"""
import time
import os
from selenium import webdriver
from PIL import Image, ImageChops

DIR_NAME = os.path.abspath(os.path.join(os.getcwd(), '..'))
DRIVER_EXE = os.path.join(DIR_NAME, 'utils', 'chromedriver')

# todo 1.打开页面，定位验证码背景图截图保存
driver = webdriver.Chrome(executable_path=DRIVER_EXE)
driver.get('http://www.porters.vip/captcha/jigsawCanvas.html')
driver.maximize_window()
before_image_box = driver.find_element_by_css_selector('#imagebox')    # todo 验证码背景图元素
before_image_box.screenshot('before.png')  # todo 截图保存
time.sleep(4)

# todo 2.获取滑块元素并按下鼠标
jigsawCircle = driver.find_element_by_css_selector('#jigsawCircle')
action = webdriver.ActionChains(driver)
action.click_and_hold(jigsawCircle).perform()   # todo 按下鼠标保持不松开
time.sleep(4)

# todo 3. 隐藏圆角矩形，并截图缺口背景图保存
script = "document.querySelectorAll('#missblock')[0].style.visibility='hidden'"
driver.execute_script(script)   # todo 隐藏圆角矩形
after_image_box = driver.find_element_by_css_selector('#imagebox')    # todo 验证码背景图元素
after_image_box.screenshot('after.png')  # todo 截图保存
time.sleep(4)

# todo 4. 打开对比截图，对比像素的不同，并获取图片差异位置坐标信息
image_before = Image.open(os.path.join(DIR_NAME, 'chapter09', 'before.png'))     # todo 打开对比截图
image_after = Image.open(os.path.join(DIR_NAME, 'chapter09', 'after.png'))     # todo 打开对比截图
diff = ImageChops.difference(image_before, image_after)     # todo 对比像素的不同
diff_position = diff.getbbox()      # todo 获取图片差异位置坐标信息
print(diff_position)    # (x1, y1, x2, y2) 左、上、右、下
time.sleep(4)

# todo 5.移动滑块
position = diff_position[0]     # todo 获取left位置
action.move_by_offset(position, 0)  # todo 移动滑块
action.release().perform()  # todo 松开鼠标


time.sleep(5)
driver.close()